package com.smileus.integration.cluster.divert;

import java.util.Map;

import com.smileus.common.CallInfo;
import com.smileus.common.Constants;
import com.smileus.common.Env;
import com.smileus.common.Param;
import com.smileus.service.ClusterService;

public class RandomDiverter implements Diverter {
	protected static ClusterService clusterService = Env.getBean("defaultClusterService", ClusterService.class);

	public String getUrl(String serviceId) {
		String sysDomain = clusterService.getSysDomain(serviceId);
		int weights = clusterService.getTotalWeight(sysDomain);
		int randomValue = getRandomValue(weights);

		return ascertain(clusterService.getCloseMapBySysDomain(sysDomain), randomValue);
	}

	public static int getRandomValue(int weights) {
		return (int) (1 + Math.random() * weights);
	}

	// 判断具体落在那个区间
	public String ascertain(Map<CloseInterval, String> map, int randomValue) {
		String url = null;
		for (Map.Entry<CloseInterval, String> entry : map.entrySet()) {
			if (entry.getKey().in(randomValue)) {
				return entry.getValue() + Constants.WSDL;
			}
		}
		return url;
	}

	// 组装CallInfo
	public CallInfo assemCallInfo(String serviceId, Param... params) {
		String url = getUrl(serviceId);
		CallInfo callInfo = clusterService.getCallInfo(serviceId);
		callInfo.setParams(params);
		callInfo.setUrl(url);
		return callInfo;
	}
}
